<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .active {
            color: red;
        }

        p {
            display: none;
        }

        .show {
            display: block;
        }
    </style>
</head>

<body>

    <div class="tab">
        <button class="active">1</button>
        <button>2</button>
        <button>3</button>

        <p class="show">111</p>
        <p>22</p>
        <p>33</p>
    </div>



    <div class="tt">
        <button class="active">1</button>
        <button>2</button>
        <button>3</button>
        <button>42</button>
        <button>5</button>

        <p class="show">111</p>
        <p>22</p>
        <p>33</p>
        <p>44</p>
        <p>55</p>
    </div>



    <script>
        // ....

        // const oTab = document.querySelector('.tab');
        // const oBtns = oTab.querySelectorAll('button');
        // const oPs = oTab.querySelectorAll('p');

        // oBtns.forEach((v, i) => {
        //     v.index = i;
        // })

        // oTab.onclick = function (e) {
        //     const target = e.target;
        //     if (target.tagName === 'BUTTON') {
        //         oBtns.forEach((v, i) => {
        //             v.classList.remove('active');
        //             oPs[i].classList.remove('show');
        //         })
        //         target.classList.add('active');
        //         oPs[target.index].classList.add('show');
        //     }
        // }



        // 构造函数的封装   对象
        //    变量变成属性
        //    函数变成了方法

        //    重点注意   this指向

        function Tab(ele) {
            this.oTab = document.querySelector(ele);
            this.oBtns = this.oTab.querySelectorAll('button');
            this.oPs = this.oTab.querySelectorAll('p');
            this.init();
        }


        Tab.prototype.init = function () {
            this.oBtns.forEach((v, i) => {
                v.index = i;
            })
            this.oTab.onclick = e => {
                const target = e.target;
                if (target.tagName === 'BUTTON') {
                    this.oBtns.forEach((v, i) => {
                        v.classList.remove('active');
                        this.oPs[i].classList.remove('show');
                    })
                    target.classList.add('active');
                    this.oPs[target.index].classList.add('show');
                }
            }
        }



        new Tab('.tab');



        new Tab('.tt');


    </script>


</body>

</html>